package com.training1.core.modules.service;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.training1.core.common.exception.ExcelException;
import com.training1.core.common.global.signIn.LoginInfoUtil;
import com.training1.core.common.service.CrudService;
import com.training1.core.entity.ChargeEntity;
import com.training1.core.entity.MemberEntity;
import com.training1.core.entity.SystemParamEntity;
import com.training1.core.exception.BusinessException;
import com.training1.core.modules.dao.ChargeDao;
import com.training1.core.modules.dao.DailyChargeDao;
import com.training1.core.modules.dao.MemberDao;
import com.training1.core.modules.dao.SystemSettingsDao;
import com.training1.util.ImportExcel;
import com.training1.util.SequenceNumberUtil;

@Service
@Transactional
public class DailyChargeService extends CrudService<ChargeDao,ChargeEntity>{
	
	@Resource
	private MemberDao memberDao;
	@Resource
	private DailyChargeDao dcDao;
	
	@Resource
	private SystemSettingsDao systemSettingDao;
	
	/*
	 *上传文件
	 */
	@Transactional
	public Map<String, String> upload(MultipartFile file) {
		InputStream in = null;
		try {
			in = file.getInputStream();
		} catch (IOException e1) {
			
			e1.printStackTrace();
		}
		String originalFilename = file.getOriginalFilename();
		Map<String,String> map = null;
		if (file != null && originalFilename != null && originalFilename.length() > 0) {
			// 存储文件的物理路径
			String file_path = "D:\\upload\\";
			// 文件新名称
			String newfileName = new Date().getTime() + originalFilename.substring(originalFilename.lastIndexOf("."));
			// 创建文件
			File newFile = new File(file_path + newfileName);
			// 判断父路径是否存在
			if (!newFile.getParentFile().exists()) {
				// 创建父路径
				newFile.getParentFile().mkdirs();
			}
			try {
				// 创建文件
				file.transferTo(newFile);
				//验证excel表中数据
				map = ImportExcel.validate2(in, memberDao, newFile.getAbsolutePath());
				//将文件路径存入map,用于返回给前台，让批量提现获取路径。
				map.put("url", newFile.getAbsolutePath());
			} catch (ExcelException e) {
				e.printStackTrace();
				//存放错误信息
				map = new HashMap<String,String>();
				map.put("result", "err");
				map.put("errMsg", e.getErrMsg().toString().substring(e.getErrMsg().toString().indexOf('[')+1, e.getErrMsg().toString().indexOf(']')));
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} 
		}
		return map;
	}
	/*
	 * 每日打款导入
	 */
	@Transactional
	public Map<String, String> charge(String filePath,String loginAccount) {
		Workbook wb;
		File source;
		Sheet sheet;
		Map<String,String> result = new HashMap<>();
		Integer count = 0;
		BigDecimal total = new BigDecimal(0.00);
		
		try {
			source = new File(filePath);
			wb = ImportExcel.getwb(source);
			sheet = wb.getSheetAt(0);
			int lastRowNum = sheet.getLastRowNum();
				try {
					for(int i=1 ; i <= lastRowNum ; i++){
						Row row = sheet.getRow(i);
						if(row == null)continue;
						//得到单元格的值
						String cellPhone = ImportExcel.getCellValue(row.getCell(1));
						BigDecimal cash = new BigDecimal(ImportExcel.getCellValue(row.getCell(2)));
						Map<String,Object> param = new HashMap<>();
						param.put("cellPhone", cellPhone);
						param.put("loginAccount", loginAccount);
						
						MemberEntity mem = memberDao.findMemberByCell(cellPhone);
						if(mem != null){
//							得到该会员原有的余额
							BigDecimal oldAvaibleCassh = mem.getAvaibleCash();
							
							BigDecimal newAvaibleCassh = oldAvaibleCassh.add(cash);
							param.put("avaibleCash", newAvaibleCassh);
							
							if(dcDao.updateAvaibleCash(param)!=1){
								result.put("err", "导入打款失败,手机号"+cellPhone);
								throw new BusinessException(result);
							}
							
						}
						count++;
						total=total.add(cash);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		result.put("success", "充值成功,合计"+count+"笔,共"+total+"元");
		return result;
	}
	
	
	
}